package com.ys.service.report.impl;

import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.report.ReDeptRevenueExpenditure;
import com.ys.mapper.report.ReDeptRevenueExpenditureDiyMapper;
import com.ys.mapper.report.ReDeptRevenueExpenditureMapper;
import com.ys.service.report.ReDeptRevenueExpenditureService;
import com.ys.util.DateUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("reDeptRevenueExpenditureService")
public class ReDeptRevenueExpenditureServiceImpl implements ReDeptRevenueExpenditureService {

	@Autowired
	private ReDeptRevenueExpenditureDiyMapper reDeptRevenueExpenditureDiyMapper;
	@Autowired
	private ReDeptRevenueExpenditureMapper reDeptRevenueExpenditureMapper;

	/**
	 * 新增
	 */
	@Override
	public int add(ReDeptRevenueExpenditure reDeptRevenueExpenditure) {
		reDeptRevenueExpenditure.setStatus(1);
		int result = reDeptRevenueExpenditureMapper.insert(reDeptRevenueExpenditure);
		return result;
	}

	/**
	 * 修改
	 */
	@Override
	public int update(ReDeptRevenueExpenditure reDeptRevenueExpenditure) {
		reDeptRevenueExpenditure.setStatus(1);
		int result = reDeptRevenueExpenditureMapper.update(reDeptRevenueExpenditure);
		return result;
	}

	/**
	 * 统计部门收支表
	 * countMonth：要统计的年月，格式：yyyy-MM
	 */
	@Override
	public void countReDeptRevenueExpenditure(String countMonth)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date theMonth = sdf.parse(countMonth);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(theMonth);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;  // 因为月份是从 0 开始计数的，所以要 +1

		calendar.add(Calendar.MONTH, +1);//下个月
		String endTime = sdf.format(calendar.getTime());

		//获取所有运营公司数据
		List<TcwAccountCountForCompany> applyList = new TcwAccountCountForCompany()
				.setBDeleted(0)
				//.setEffectStock(1)
				.where("A.VZhLx !='运营账户'")
				.queryList();

		//获取当年收支报告表
		List<ReDeptRevenueExpenditure> thisYearList = new ReDeptRevenueExpenditure().setYearNum(year).queryList();

		//******收入******
		//根据公司编码、公司账户流水,统计部门收支*收入,不包括普通运营账户
		List<Map<String, Object>> noComIn = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureNoComIn(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计部门收支*收入,包括普通运营账户
		List<Map<String, Object>> withComIn = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureWithComIn(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");

		//******支出******
		//根据公司编码、公司账户流水,统计部门收支*支出,不包括普通运营账户
		List<Map<String, Object>> noComOut = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureNoComOut(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计部门收支*支出,包括普通运营账户
		List<Map<String, Object>> withComOut = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureWithComOut(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");

		//******利润******
		//根据公司编码、公司账户流水,统计部门收支*利润,不包括普通运营账户
		List<Map<String, Object>> noCom = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureNoCom(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计部门收支*利润,包括普通运营账户
		List<Map<String, Object>> withCom = reDeptRevenueExpenditureDiyMapper.countAccountCountByDeptRevenueExpenditureWithCom(countMonth+"-01 00:00:00",endTime+"-01 00:00:00");

		int lastDay = new DateUtil().getMonthLastDay(countMonth);//获取月份的最后一天
		//******上月最后一天的历史资金******
		//根据公司编码、公司账户流水,统计上月最后一天的历史资金，支出,不包括普通运营账户
		List<Map<String, Object>> countMonthLastDayCountNoComOut = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountNoComOut(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计上月最后一天的历史资金，支出,包括普通运营账户
		List<Map<String, Object>> countMonthLastDayCountWithComOut = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountWithComOut(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计上月最后一天的历史资金，收入,不包括普通运营账户
		List<Map<String, Object>> countMonthLastDayCountNoComIn = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountNoComIn(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");
		//根据公司编码、公司账户流水,统计上月最后一天的历史资金，收入,包括普通运营账户
		List<Map<String, Object>> countMonthLastDayCountWithComIn = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountWithComIn(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");
		//上月最后一天的历史资金,不包括普通运营账户
		List<Map<String, Object>> monthLastDayCountNoCom = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountNoCom(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");
		//上月最后一天的历史资金,包括普通运营账户
		List<Map<String, Object>> monthLastDayCountWithCom = reDeptRevenueExpenditureDiyMapper.countMonthLastDayCountWithCom(countMonth+"-"+lastDay+" 00:00:00",endTime+"-01 00:00:00");

		ReDeptRevenueExpenditure toZero = new ReDeptRevenueExpenditure();
		toZero.setYearNum(year);
		reDeptRevenueExpenditureDiyMapper.updateMonthLastDayCountToZero(toZero);

		if(applyList!=null && applyList.size()>0){

			BigDecimal monthLastDayCountByYYZH = BigDecimal.ZERO;
			BigDecimal monthLastDayCountByYYZHOut = BigDecimal.ZERO;
			BigDecimal monthLastDayCountByYYZHIn = BigDecimal.ZERO;
			for(TcwAccountCountForCompany companyItem:applyList){
				String vGsBm = companyItem.getVGsBm();//运营公司编码
				String vGsJc = companyItem.getVGsJc();//运营公司简称
				String accountType = companyItem.getVZhLx();//运营公司账户类型
				BigDecimal monthLastDayCountByNo = BigDecimal.ZERO;
				BigDecimal monthLastDayCountByNoOut = BigDecimal.ZERO;
				BigDecimal monthLastDayCountByNoIn = BigDecimal.ZERO;
				if(thisYearList!=null && thisYearList.size()>0){
					//收入
					setReDeptRevenueExpenditure(noComIn,thisYearList,year,month,vGsBm,vGsJc,0,accountType);
					//支出
					setReDeptRevenueExpenditure(noComOut,thisYearList,year,month,vGsBm,vGsJc,1,accountType);
					//利润
					setReDeptRevenueExpenditure(noCom,thisYearList,year,month,vGsBm,vGsJc,2,accountType);
				}else {//新增
					List<ReDeptRevenueExpenditure> newList = new ArrayList<>();
					//收入
					setReDeptRevenueExpenditure(noComIn,newList,year,month,vGsBm,vGsJc,0,accountType);
					//支出
					setReDeptRevenueExpenditure(noComOut,newList,year,month,vGsBm,vGsJc,1,accountType);
					//利润
					setReDeptRevenueExpenditure(noCom,newList,year,month,vGsBm,vGsJc,2,accountType);
				}

				//获取上月最后一天的历史资金
				if(monthLastDayCountNoCom!=null && monthLastDayCountNoCom.size()>0){
					List<Map<String, Object>> monthLastDayCountNoComByBm = monthLastDayCountNoCom.stream().filter(item->item.get("accountCode").toString().equals(vGsBm)).collect(Collectors.toList());
					if(monthLastDayCountNoComByBm.size()>0){
						monthLastDayCountByNo = (BigDecimal)monthLastDayCountNoComByBm.get(0).get("countFje");
					}
				}
				if(countMonthLastDayCountNoComOut!=null && countMonthLastDayCountNoComOut.size()>0){
					List<Map<String, Object>> newByBm1 = countMonthLastDayCountNoComOut.stream().filter(item->item.get("accountCode").toString().equals(vGsBm)).collect(Collectors.toList());
					if(newByBm1.size()>0){
						monthLastDayCountByNoOut = (BigDecimal)newByBm1.get(0).get("countFje");
					}
				}
				if(countMonthLastDayCountNoComIn!=null && countMonthLastDayCountNoComIn.size()>0){
					List<Map<String, Object>> newByBm = countMonthLastDayCountNoComIn.stream().filter(item->item.get("accountCode").toString().equals(vGsBm)).collect(Collectors.toList());
					if(newByBm.size()>0){
						monthLastDayCountByNoIn = (BigDecimal)newByBm.get(0).get("countFje");
					}
				}
				//修改上月最后一天的历史资金
				updateMonthLastDayCountPublic(vGsBm,year,0,monthLastDayCountByNoIn);
				updateMonthLastDayCountPublic(vGsBm,year,1,monthLastDayCountByNoOut);
				updateMonthLastDayCountPublic(vGsBm,year,2,monthLastDayCountByNo);

			}
			if(monthLastDayCountWithCom!=null && monthLastDayCountWithCom.size()>0){
				monthLastDayCountByYYZH = (BigDecimal)monthLastDayCountWithCom.get(0).get("countFje");
			}
			if(countMonthLastDayCountWithComOut!=null && countMonthLastDayCountWithComOut.size()>0){
				monthLastDayCountByYYZHOut = (BigDecimal)countMonthLastDayCountWithComOut.get(0).get("countFje");
			}
			if(countMonthLastDayCountWithComIn!=null && countMonthLastDayCountWithComIn.size()>0){
				monthLastDayCountByYYZHIn = (BigDecimal)countMonthLastDayCountWithComIn.get(0).get("countFje");
			}
			setReDeptRevenueExpenditureWithCom(withComIn,year,month,0);
			setReDeptRevenueExpenditureWithCom(withComOut,year,month,1);
			setReDeptRevenueExpenditureWithCom(withCom,year,month,2);
			//修改上月最后一天的历史资金
			updateMonthLastDayCountPublic("YYZH",year,0,monthLastDayCountByYYZHIn);
			updateMonthLastDayCountPublic("YYZH",year,1,monthLastDayCountByYYZHOut);
			updateMonthLastDayCountPublic("YYZH",year,2,monthLastDayCountByYYZH);
		}
	}

	//修改上月最后一天的历史资金
	public void updateMonthLastDayCountPublic(String vGsBm,int year,int countType,BigDecimal monthLastDayCount){
		ReDeptRevenueExpenditure reDeptRevenueExpenditure = new ReDeptRevenueExpenditure();
		reDeptRevenueExpenditure.setAccountCode(vGsBm);
		//上月最后一天的历史资金,按照账户编码
		//统计类型为利润时，填入上月最后一天历史资金。否则填入0
		if(countType==2){//统计类型（0收入、1支出、2利润）
			reDeptRevenueExpenditure.setMonthLastDayCount(monthLastDayCount);
		}else {
			reDeptRevenueExpenditure.setMonthLastDayCount(BigDecimal.ZERO);
		}
		reDeptRevenueExpenditure.setYearNum(year);
		reDeptRevenueExpenditure.setCountType(countType);
		reDeptRevenueExpenditureDiyMapper.updateMonthLastDayCount(reDeptRevenueExpenditure);
	}

	//分类新增、修改，不包括普通运营账户
	public void setReDeptRevenueExpenditure(List<Map<String, Object>> noCom, List<ReDeptRevenueExpenditure> thisYearList,
											int year, int month,String vGsBm,String vGsJc,int countType,String accountType){
		//根据公司编码获取统计信息
		List<Map<String, Object>> noComInByBm = noCom.stream().filter(item->item.get("accountCode").equals(vGsBm)).collect(Collectors.toList());
		//String accountType = "";
		BigDecimal count = BigDecimal.ZERO;
		String dealType = "";
		if(noComInByBm.size()>0){
			for(Map<String, Object> noComInByBmItem:noComInByBm){
				count = noComInByBmItem.get("countFje")!=null?(BigDecimal)noComInByBmItem.get("countFje"):BigDecimal.ZERO;
				accountType = noComInByBmItem.get("accountTypeName")!=null?noComInByBmItem.get("accountTypeName").toString():"";
				String dealType1 =  noComInByBmItem.get("dealType")!=null?noComInByBmItem.get("dealType").toString():"";
				List<ReDeptRevenueExpenditure> thisYearListByBmAndIn = thisYearList.stream()
						.filter(item->item.getAccountCode().equals(vGsBm) && item.getCountType()==countType && item.getDealType().equals(dealType1))
						.collect(Collectors.toList());
				if(thisYearListByBmAndIn.size()>0){//修改
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,vGsBm,vGsJc,accountType,count,dealType1,countType,"update",thisYearListByBmAndIn.get(0));
					reDeptRevenueExpenditureMapper.update(reDeptRevenueExpenditure);
				}else {//新增
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,vGsBm,vGsJc,accountType,count,dealType1,countType,"add",null);
					reDeptRevenueExpenditureMapper.insert(reDeptRevenueExpenditure);
				}
			}

		}
		else {
			List<ReDeptRevenueExpenditure> thisYearListByBmAndIn = thisYearList.stream()
					.filter(item->item.getAccountCode().equals(vGsBm) && item.getCountType()==countType)
					.collect(Collectors.toList());
			if(thisYearListByBmAndIn.size()>0){//修改
				//若统计结果为0，则将该公司该月的统计数据更新为0
				for(ReDeptRevenueExpenditure item:thisYearListByBmAndIn){
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,vGsBm,vGsJc,accountType,BigDecimal.ZERO,null,countType,"update",item);
					reDeptRevenueExpenditureMapper.update(reDeptRevenueExpenditure);
				}

			}
			//若无、同时结果为0也需要新增
			else {//新增
				ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,vGsBm,vGsJc,accountType,BigDecimal.ZERO,dealType,countType,"add",null);
				reDeptRevenueExpenditureMapper.insert(reDeptRevenueExpenditure);
			}
		}


		/*
		//包括普通运营账户
		if(withCom!=null && withCom.size()>0){
			for(Map<String, Object> withComItem:withCom){
				String accountTypeIn = withComItem.get("accountTypeName")!=null?withComItem.get("accountTypeName").toString():"";
				BigDecimal countIn = withComItem.get("countFje")!=null?(BigDecimal)withComItem.get("countFje"):BigDecimal.ZERO;
				String dealTypeWith =  withComItem.get("dealType")!=null?withComItem.get("dealType").toString():"";
				List<ReDeptRevenueExpenditure> thisYearListByBmAndInWithCom = thisYearList.stream()
						.filter(item->item.getAccountCode().equals("YYZH") && item.getDealType().equals(dealTypeWith)).collect(Collectors.toList());
				if(thisYearListByBmAndInWithCom.size()>0){//修改
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,"YYZH",accountTypeIn,accountTypeIn,countIn,dealTypeWith,countType,"update",thisYearListByBmAndInWithCom.get(0));
					reDeptRevenueExpenditureMapper.update(reDeptRevenueExpenditure);
				}else {//新增
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,"YYZH",accountTypeIn,accountTypeIn,countIn,dealTypeWith,countType,"add",null);
					reDeptRevenueExpenditureMapper.insert(reDeptRevenueExpenditure);
				}
			}

		}

		 */

	}

	//分类新增、修改，包括普通运营账户
	public void setReDeptRevenueExpenditureWithCom(List<Map<String, Object>> withCom,int year, int month,int countType){
		if(withCom!=null && withCom.size()>0){
			for(Map<String, Object> withComItem:withCom){
				String accountTypeIn = withComItem.get("accountTypeName")!=null?withComItem.get("accountTypeName").toString():"";
				BigDecimal countIn = withComItem.get("countFje")!=null?(BigDecimal)withComItem.get("countFje"):BigDecimal.ZERO;
				String dealTypeWith =  withComItem.get("dealType")!=null?withComItem.get("dealType").toString():"";
				List<ReDeptRevenueExpenditure> thisYearListByBmAndInWithCom = new ReDeptRevenueExpenditure()
						.setYearNum(year)
						.setAccountCode("YYZH")
						.setDealType(dealTypeWith)
						.setCountType(countType)
						.queryList();
				//List<ReDeptRevenueExpenditure> thisYearListByBmAndInWithCom = thisYearList.stream()
						//.filter(item->item.getAccountCode().equals("YYZH") && item.getDealType().equals(dealTypeWith)).collect(Collectors.toList());
				if(thisYearListByBmAndInWithCom!=null && thisYearListByBmAndInWithCom.size()>0){//修改
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,"YYZH",accountTypeIn,accountTypeIn,countIn,dealTypeWith,countType,"update",thisYearListByBmAndInWithCom.get(0));
					reDeptRevenueExpenditureMapper.update(reDeptRevenueExpenditure);
				}else {//新增
					ReDeptRevenueExpenditure reDeptRevenueExpenditure = setReDeptRevenueExpenditure(year,month,"YYZH",accountTypeIn,accountTypeIn,countIn,dealTypeWith,countType,"add",null);
					reDeptRevenueExpenditureMapper.insert(reDeptRevenueExpenditure);
				}
			}

		}
	}



	//数据填入
	public ReDeptRevenueExpenditure setReDeptRevenueExpenditure(int year, int month, String accountCode, String accountName, String accountType,
																BigDecimal count,String dealType, int countType,String addOrUpdate,
																ReDeptRevenueExpenditure thisYearListByBm){
		ReDeptRevenueExpenditure reDeptRevenueExpenditure = new ReDeptRevenueExpenditure();
		reDeptRevenueExpenditure.setAccountCode(accountCode);//账户编码
		reDeptRevenueExpenditure.setAccountName(accountName);//账户名称
		reDeptRevenueExpenditure.setAccountType(accountType);//账户类型
		reDeptRevenueExpenditure.setYearNum(year);//年份
		reDeptRevenueExpenditure.setCountType(countType);//统计类型（0收入、1支出、2利润）
		reDeptRevenueExpenditure.setMonthLastDayCount(BigDecimal.ZERO);//上月最后一天的历史资金,按照账户编码
		if(month==1){
			reDeptRevenueExpenditure.setJanCount(count);
		}else if(month==2){
			reDeptRevenueExpenditure.setFebCount(count);
		}else if(month==3){
			reDeptRevenueExpenditure.setMarCount(count);
		}else if(month==4){
			reDeptRevenueExpenditure.setAprCount(count);
		}else if(month==5){
			reDeptRevenueExpenditure.setMayCount(count);
		}else if(month==6){
			reDeptRevenueExpenditure.setJunCount(count);
		}else if(month==7){
			reDeptRevenueExpenditure.setJulCount(count);
		}else if(month==8){
			reDeptRevenueExpenditure.setAugCount(count);
		}else if(month==9){
			reDeptRevenueExpenditure.setSeptCount(count);
		}else if(month==10){
			reDeptRevenueExpenditure.setOctCount(count);
		}else if(month==11){
			reDeptRevenueExpenditure.setNovCount(count);
		}else {//12
			reDeptRevenueExpenditure.setDecCount(count);
		}

		if(addOrUpdate.equals("add")){//新增
			reDeptRevenueExpenditure.setYearCount(count);//累计
			reDeptRevenueExpenditure.setStatus(1);
			if(dealType!=null)reDeptRevenueExpenditure.setDealType(dealType);//交易类型
		}else {//修改
			reDeptRevenueExpenditure.setStatus(1);
			reDeptRevenueExpenditure.setId(thisYearListByBm.getId());
			BigDecimal yearCount = count;
			if(month>1 && thisYearListByBm.getJanCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getJanCount());
			}
			if(month>2 && thisYearListByBm.getFebCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getFebCount());
			}
			if(month>3 && thisYearListByBm.getMarCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getMarCount());
			}
			if(month>4 && thisYearListByBm.getAprCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getAprCount());
			}
			if(month>5 && thisYearListByBm.getMayCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getMayCount());
			}
			if(month>6 && thisYearListByBm.getJunCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getJunCount());
			}
			if(month>7 && thisYearListByBm.getJulCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getJulCount());
			}
			if(month>8 && thisYearListByBm.getAugCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getAugCount());
			}
			if(month>9 && thisYearListByBm.getSeptCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getSeptCount());
			}
			if(month>10 && thisYearListByBm.getOctCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getOctCount());
			}
			if(month>11 && thisYearListByBm.getNovCount()!=null){
				yearCount = yearCount.add(thisYearListByBm.getNovCount());
			}
			reDeptRevenueExpenditure.setYearCount(yearCount);//累计
		}


		return reDeptRevenueExpenditure;
	}




}
